import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:uuid/uuid.dart';
import '../../common/index.dart';
import '../index.dart';

class ReleaseController extends GetxController {
  ReleaseController();

  final TextEditingController title_controller = TextEditingController();
  final TextEditingController description_controller = TextEditingController();
  final RxList<XFile> selected_images = <XFile>[].obs;
  final ImagePicker _picker = ImagePicker();
  final PostService _post_service = PostService();
  final ImageStorageService _image_storage_service = ImageStorageService();

  // 加载状态
  RxBool is_loading = false.obs;

  _init_data() {
    update(["release"]);
  }

  void onBack() {
    RouteUtil.pop();
  }

  void onRelease() async {
    // 验证表单
    if (title_controller.text.isEmpty) {
      SmartDialogHelper.show_error('please add title');
      return;
    }
    if (description_controller.text.isEmpty) {
      SmartDialogHelper.show_error('please add description');
      return;
    }
    if (selected_images.isEmpty) {
      SmartDialogHelper.show_error('please select at least one image');
      return;
    }

    // 显示加载对话框 - 使用标准Flutter方式
    if (Get.context != null) {
      show_loading_dialog(Get.context!);
    }

    try {
      // 1. 保存图片到本地永久存储
      final String saved_image_paths = await _image_storage_service.save_images(
        selected_images,
      );

      debugPrint('已保存图片路径: $saved_image_paths'); // 添加调试信息

      // 2. 创建帖子对象
      final String post_id = 'post_${Uuid().v4()}';
      final String current_time = DateTime.now().millisecondsSinceEpoch
          .toString();

      // 从用户服务获取当前用户ID
      final current_user = UserService().get_now_user();
      final user_id = current_user?.id ?? 'anonymous';

      // 创建帖子模型
      final new_post = PostModel(
        post_id: post_id,
        post_title: title_controller.text,
        post_detail: description_controller.text,
        post_content_list: [], // 初始无评论
        post_image_list: saved_image_paths,
        post_created_time: current_time,
        user_id: user_id,
      );

      // 3. 保存帖子到SP
      final bool success = await _post_service.create_post(new_post);

      // 4. 保存帖子id到用户数据
      current_user?.post_lists?.add(post_id);
      UserService().set_user(current_user!);

      // 关闭加载对话框
      if (Get.context != null) {
        close_loading_dialog(Get.context!);
      }

      if (success) {
        // 清空表单
        title_controller.clear();
        description_controller.clear();
        selected_images.clear();

        // 刷新社区界面
        Get.find<CommunityController>().refresh_posts();
        RouteUtil.go(RouteNames.community);

        SmartDialogHelper.show_success('Published successfully!');
      }
    } catch (e) {
      SmartDialogHelper.show_error('Failed to publish: $e');
    }
  }

  Future<void> pick_image() async {
    try {
      // Hide keyboard first
      FocusManager.instance.primaryFocus?.unfocus();

      is_loading.value = true;
      update(["release"]);

      final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
      if (image != null) {
        selected_images.add(image);
      }
    } finally {
      is_loading.value = false;
      update(["release"]);
    }
  }

  void remove_image(int index) {
    if (index >= 0 && index < selected_images.length) {
      selected_images.removeAt(index);
      update(["release"]);
    }
  }

  @override
  void onReady() {
    super.onReady();
    _init_data();
  }

  @override
  void onClose() {
    title_controller.dispose();
    description_controller.dispose();
    super.onClose();
  }

  // 显示加载对话框的方法
  void show_loading_dialog(BuildContext context) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) => Dialog(
        backgroundColor: Colors.black.withOpacity(0.7),
        child: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: const [
              CircularProgressIndicator(color: Colors.white),
              SizedBox(height: 20),
              Text('Publishing...', style: TextStyle(color: Colors.white)),
            ],
          ),
        ),
      ),
    );
  }

  // 关闭加载对话框的方法
  void close_loading_dialog(BuildContext context) {
    if (Navigator.of(context).canPop()) {
      Navigator.of(context).pop();
    }
  }
}
